// import { config } from '@vue/test-utils'
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index'
import router from '@/router/index'
//创建副本
const instance = axios.create({
  baseURL: '/api'
})

//设置拦截器
//请求拦截器
instance.interceptors.request.use(
  config => {
    // console.log(store.state.user.token);
    if (store.getters.token) {
      config.headers['Authorization'] = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
//响应拦截器
instance.interceptors.response.use(
  response => {
    //结构赋值
    const {
      data: { message, success }
    } = response
    //判断响应是否成功
    if (success) {
      return response.data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  error => {
    if (
      error.response &&
      error.response.data &&
      error.response.data.code === 10002
    ) {
      store.dispatch('user/logout')
      Message.info('登录超时,请重新登录开卷')
      router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
    }
    return Promise.reject(error)
  }
)

//导出
export default instance
